/***
 * 切换表格头弹窗
 */
import React, { useState, useCallback, useRef, Ref } from 'react';
import { Table } from 'antd';
import BuildTitle from '@/components/BuildTitle';
import { DndProvider, useDrag, useDrop } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import update from 'immutability-helper';
import { MenuOutlined } from '@ant-design/icons';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import _ from 'lodash';
import { SchemaManageAPI } from '@/components/SchemaComponent/SchemaManage/type';
import { OneModal } from '@/components/one-ui';
import MyIcon from '@/components/MyIcon';
import { IOneModalRef } from '@/pages/type';

const type = 'DraggableBodyRow';

const DraggableBodyRow = ({
  //拖动排序配置
  index,
  moveRow,
  className,
  style,
  ...restProps
}: any) => {
  const ref = useRef<any>();
  const [{ isOver, dropClassName }, drop] = useDrop({
    accept: type,
    collect: (monitor: any) => {
      const { index: dragIndex } = monitor.getItem() || {};
      if (dragIndex === index) {
        return {};
      }
      return {
        isOver: monitor.isOver(),
        dropClassName: dragIndex < index ? ' drop-over-downward' : ' drop-over-upward',
      };
    },
    drop: (item: any) => {
      moveRow(item.index, index);
    },
  });
  const [, drag] = useDrag({
    type,
    item: { index },
    collect: (monitor) => {
      return {
        isDragging: monitor.isDragging(),
      };
    },
  });
  drop(drag(ref));

  return <tr ref={ref} className={`${className}${isOver ? dropClassName : ''}`} style={{ cursor: 'move', ...style }} {...restProps} />;
};

export const ChangeColumns: React.FC<SchemaManageAPI.IChangeColumns> = ({ onClose, columnsList, onOk }) => {
  const className = 'class' + parseInt(String(Math.random() * 1000000));
  const title = <BuildTitle title={'设置显示列'} className={className} />;

  /** 处理选脏鞥你显示列 */
  const resetData = (column: any[]) => {
    let selectKeys: any[] = [];
    column?.forEach((item) => {
      if (item?.visible) {
        selectKeys.push(item?.key ?? item?.dataIndex);
      }
    });
    return {
      selectKeys,
    };
  };

  const [data, setData] = useState<any>(columnsList);
  const [selectKeys, setSelect] = useState<any>(resetData(columnsList).selectKeys);

  /** modal ref */
  const columnsModalRef: Ref<IOneModalRef> = useRef(null);

  /** 关闭弹窗 */
  const onCloseModal = () => {
    if (columnsModalRef) {
      if (columnsModalRef.current) {
        if (columnsModalRef.current.onModalCancel) {
          columnsModalRef.current.onModalCancel();
        }
      }
    }
  };

  /** 表格列配置 */
  const columns = [
    {
      title: '列名',
      dataIndex: 'title',
      key: 'title',
      render: (text) => {
        if (typeof text == 'string') {
          return text;
        } else {
          return text();
        }
      },
    },
    // {
    //   title: 'dataIndex',
    //   dataIndex: 'dataIndex',
    //   key: 'dataIndex',
    // },
    {
      title: '拖动调整顺序',
      dataIndex: 'option',
      key: 'option',
      render: (text: any, record: Record<string, any> | any) => {
        return <>{record?.unDrag ? <MyIcon type="icon-pushpin" /> : <MenuOutlined />}</>;
      },
    },
  ];

  const onModalOk = () => {
    onOk(data);
    // onClose();
    onCloseModal();
  };

  const components = {
    body: {
      row: DraggableBodyRow,
    },
  };

  const moveRow: any = useCallback(
    (dragIndex: any, hoverIndex: any) => {
      const dragRow = data[dragIndex]; //拖拽
      const quiltRow = data[hoverIndex]; //被移动
      if (!dragRow?.unDrag && !quiltRow?.unDrag) {
        //固定列不可调整位置
        setData(
          update(data, {
            $splice: [
              [dragIndex, 1],
              [hoverIndex, 0, dragRow],
            ],
          }),
        );
      }
    },
    [data],
  );

  const onSelectChange = (key: any[], record: any[]) => {
    let newSelect = _.cloneDeep(key);
    let newColumns = data?.map((item: any) => {
      if (newSelect?.includes(item?.key || item?.dataIndex)) {
        return {
          ...item,
          visible: true,
        };
      } else {
        return {
          ...item,
          visible: false,
        };
      }
    });
    setData(newColumns);
    setSelect(newSelect);
  };

  return (
    <OneModal
      ref={columnsModalRef}
      getContainer={false}
      open={true}
      onCancel={onClose}
      centered={true}
      className={className}
      transitionName=""
      title={title}
      onOk={onModalOk}
      bodyStyle={{ padding: 0, height: window.screen.height * 0.4 }}
      width={window.screen.width * 0.4}
    >
      <ScrollBarLayout
        style={{
          padding: '1rem',
        }}
      >
        <DndProvider backend={HTML5Backend}>
          <Table
            columns={columns}
            dataSource={data}
            size={'small'}
            pagination={false}
            components={components}
            bordered
            onRow={(record: any, index: any): any => ({
              index,
              moveRow,
            })}
            rowKey={(record) => record?.key ?? record?.dataIndex}
            rowSelection={{
              type: 'checkbox',
              onChange: onSelectChange,
              columnTitle: <span style={{ whiteSpace: 'nowrap' }}>显示</span>,
              selectedRowKeys: selectKeys,
              getCheckboxProps: (record) => {
                return {
                  disabled: record?.unDrag,
                };
              },
            }}
          />
        </DndProvider>
      </ScrollBarLayout>
    </OneModal>
  );
};
